package com.jianbing.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import com.jianbing.dao.MongoDBDao;
import com.jianbing.entity.AccessToken;
import com.jianbing.entity.Customer;
import com.jianbing.entity.Result;
import com.jianbing.entity.TaskStatus;
import com.jianbing.service.NoticeDataWarehouseService;
import com.jianbing.service.ShoppingService;
import com.jianbing.util.Constants;
import com.jianbing.util.HttpClient;
import com.jianbing.util.IDCardUtil;
import com.jianbing.util.SignUtil;
import com.jianbing.util.StringFuzzyMatchUtils;
import com.jianbing.util.StringUtils;
import com.jianbing.util.TableUtil;
import com.mongodb.BasicDBObject;

import net.sf.json.JSONObject;

@Service
public class ShoppingServiceImpl implements ShoppingService {

	Logger logger = Logger.getLogger(ShoppingServiceImpl.class);

	@Autowired
	private NoticeDataWarehouseService noticeDataWarehouseService;

	@SuppressWarnings("static-access")
	@Override
	public Result getShoppingData(Result result, JSONObject json) throws Exception {
		ModelMap model = new ModelMap();
		Date now = new Date();
		JSONObject jsonParam = JSONObject.fromObject(json.get("params"));
		MongoDBDao dbDao = new MongoDBDao();
		BasicDBObject queryObject = new BasicDBObject();
		queryObject.append("appKey", jsonParam.get("appKey"));
		Customer customer = dbDao.findOne(TableUtil.customer, Customer.class, queryObject);
		if (customer == null) {
			result.setCode(102);
			result.setMsg("无效的appKey");
			return result;
		}
		AccessToken accessToken = MongoDBDao.findOne(TableUtil.accessToken, AccessToken.class, queryObject);
		if (accessToken == null || accessToken.getActiveTime() < now.getTime()) {
			result.setCode(103);
			result.setMsg("token已超时");
			return result;
		}
		if ((jsonParam.getLong("timestamp") + Constants.accessTime * 1000) < now.getTime()
				|| !SignUtil.checkSign(json.getString("sign"), jsonParam, customer.getAppSecret())) {
			result.setCode(104);
			result.setMsg("签名错误");
			return result;
		}
		// 从数据仓库获取数据并校验
		JSONObject dataJson = null;
		String phone = "";
		String name = "";
		String ID = "";
		String type = json.getString("type");
		if (type.equals(Constants.tb)) {
			String tbDataResult = HttpClient.get(Constants.tb_data_url + jsonParam.getString("orderSn"));
			if (StringUtils.isEmpty(tbDataResult) || JSONObject.fromObject(tbDataResult).getInt("code") != 0) {
				result.setCode(105);
				result.setMsg("无此订单数据");
				return result;
			}
			dataJson = JSONObject.fromObject(tbDataResult);
			if (dataJson.get("phone") != null) {
				phone = dataJson.get("phone").toString();
			}
			if (dataJson.get("auth") != null) {
				String auth = dataJson.get("auth").toString();
				if (StringUtils.isNotEmpty(auth)) {
					String[] str1 = auth.split("\\|");
					name = str1[0];
					String[] str2 = str1[1].split("已认证");
					ID = str2[0];
				}
			}
		} else if (type.equals(Constants.jd)) {
			String jdDataResult = HttpClient.get(Constants.jd_data_url + jsonParam.getString("orderSn"));
			if (StringUtils.isEmpty(jdDataResult) || JSONObject.fromObject(jdDataResult).getInt("code") != 0) {
				result.setCode(105);
				result.setMsg("无此订单数据");
				return result;
			}
			dataJson = JSONObject.fromObject(jdDataResult);
			if (dataJson.get("brief") != null) {
				JSONObject brief = dataJson.getJSONObject("brief");
				if (brief.get("phone") != null) {
					phone = brief.get("phone").toString();
				}
				if (brief.get("ID") != null) {
					ID = brief.get("ID").toString();
				}
				if (brief.get("name") != null) {
					name = brief.get("name").toString();
				}
			}
		} else {
			result.setCode(105);
			result.setMsg("无此订单数据");
			return result;
		}

		if (StringUtils.isNotEmpty(name)
				&& !StringFuzzyMatchUtils.checkStringMatching1(jsonParam.getString("name"), name)) {
			result.setCode(106);
			result.setMsg("姓名匹配失败");
			return result;
		}
		if (StringUtils.isNotEmpty(ID) && (!IDCardUtil.IDCardValidate(jsonParam.getString("ID"))
				|| !StringFuzzyMatchUtils.checkStringMatching2(jsonParam.getString("ID"), ID))) {
			result.setCode(107);
			result.setMsg("身份证号匹配失败");
			return result;
		}
		if (StringUtils.isNotEmpty(phone)
				&& !StringFuzzyMatchUtils.checkStringMatching2(jsonParam.getString("phone"), phone)) {
			result.setCode(108);
			result.setMsg("手机号码匹配失败");
			return result;
		}
		logger.info((type.equals(Constants.tb) ? "淘宝" : "京东") + "数据查询成功" + dataJson);
		// 返回数据给合作方
		model.addAttribute((type.equals(Constants.tb) ? "tbData" : "jdData"), dataJson);
		result.setData(model);
		// 向数据仓库上传用户信息
		Map<String, Object> noticeMsg = new HashMap<String, Object>();
		Map<String, String> params = new HashMap<String, String>();
		params.put("orderid", jsonParam.getString("orderSn"));
		params.put("name", jsonParam.getString("name"));
		params.put("id", jsonParam.getString("ID"));
		params.put("phone", jsonParam.getString("phone"));
		params.put("serviceType", "ecom");
		noticeMsg.put("params", params);
		noticeMsg.put("url", Constants.data_notice_url);
		noticeDataWarehouseService.producer(JSONObject.fromObject(noticeMsg).toString());
		// logger.info("通知数据仓库" + (type.equals(Constants.tb) ? "淘宝" : "京东") +
		// "用户信息 success " + noticeMsg);
		return result;
	}

	@Override
	public List<TaskStatus> queryShoppingTaskStatus(String orderSn, Integer taskId, String status, String type) {
		BasicDBObject queryObject = new BasicDBObject();
		if (StringUtils.isNotEmpty(orderSn)) {
			queryObject.append("orderSn", orderSn);
		}
		if (StringUtils.isNotEmpty(status)) {
			queryObject.append("status", status);
		}
		if (taskId != null) {
			queryObject.append("taskId", taskId);
		}

		String tableName = "";
		if (type.equals(Constants.tb)) {
			tableName = TableUtil.tbTaskStatusTable;
		} else if (type.equals(Constants.jd)) {
			tableName = TableUtil.jdTaskStatusTable;
		} else {
			return null;
		}
		List<TaskStatus> shoppingTaskStatusList = MongoDBDao.queryForList(tableName, TaskStatus.class, queryObject,
				null, null, null, null);
		return shoppingTaskStatusList;
	}

	@Override
	public void updateShoppingTaskStatus(String orderSn, Integer taskId, String status, String type) throws Exception {
		Date now = new Date();
		BasicDBObject queryObject = new BasicDBObject();
		queryObject.append("orderSn", orderSn);
		String tableName = "";
		if (type.equals(Constants.tb)) {
			tableName = TableUtil.tbTaskStatusTable;
		} else if (type.equals(Constants.jd)) {
			tableName = TableUtil.jdTaskStatusTable;
		} else {
			return;
		}
		TaskStatus shoppingTaskStatus = MongoDBDao.findOne(tableName, TaskStatus.class, queryObject);
		if (shoppingTaskStatus == null) {
			shoppingTaskStatus = new TaskStatus();
			shoppingTaskStatus.setOrderSn(orderSn);
			shoppingTaskStatus.setTaskId(taskId);
			shoppingTaskStatus.setStatus(status);
			shoppingTaskStatus.setCreateTime(now);
			shoppingTaskStatus.setUpdateTime(now);
			MongoDBDao.insert(tableName, shoppingTaskStatus);
		} else {
			shoppingTaskStatus.setStatus(status);
			shoppingTaskStatus.setUpdateTime(now);
			shoppingTaskStatus.setTaskId(taskId);
			MongoDBDao.update(tableName, queryObject, shoppingTaskStatus);
		}
	}

}
